<?php

namespace App\Http\Controllers\Shop;

use App\Http\Controllers\ShopController;
use App\Models\Shop\Address;
use App\Models\Shop\Clock;
use App\Models\Shop\Store;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\DB;
use Omnipay\Omnipay;

class DealController extends ShopController
{
    private $timeData = [
        [
            'id'    =>  1,
            'time'  =>  '配達',
            'price' =>  1.5
        ],
        [
            'id'    =>  2,
            'time'  =>  '12:20',
            'price' =>  0
        ]
    ];
    private $storeID;

    public function __construct()
    {
        parent::__construct();
        $this->storeID = \Illuminate\Support\Facades\Request::cookie('storeID') ? \Illuminate\Support\Facades\Request::cookie('storeID') : 1;
        //获取配送时间
        $clock = Clock::where('storeID', $this->storeID)->where('display', 1)->get()->toArray();
        if($clock)
        {
            $this->timeData = $clock;
        }
    }

    public function getIndex()
    {
        $this->active = 'deal';
        return view('shopWx.deal')->with(['active' => $this->active]);
    }

    public function getCheck(Request $request)
    {
        $addressData = Address::where('uid', $this->user->id)->orderBy('id', 'desc')->get()->keyBy('id');
        $bacData = [];

        foreach ($addressData as $k=>$v)
        {
            $bacData[] = [
                'id'        =>  $v->id,
                'name'      =>  $v->name,
                'phone'     =>  $v->phone,
                'address'   =>  $v->address
            ];
        }
        return view('shopWx.deal-check')->with(['address' => $bacData, 'timeData' => $this->timeData]);
    }

    public function getSelectAddress()
    {
        return view('shopWx.address-select');
    }
    public function getSelectAddressAjax()
    {
        //获取地址信息
        $address = Address::where('storeID', $this->storeID)->where('uid', $this->user->id)->orderBy('id', 'desc')->get();
        $bacData = [];
        foreach ($address as $k=>$v)
        {
            $bacData[] = [
                'id'        =>  $v->id,
                'name'      =>  $v->name,
                'phone'     =>  $v->phone,
                'address'   =>  $v->address
            ];
        }
        return json_encode([
            'code'      =>  1,
            'msg'       =>  'success',
            'data'      =>  [
                'address'   =>  $bacData
            ]
        ]);
    }

    public function getSelectTime()
    {
        return view('shopWx.time-select')->with(['timeData' => $this->timeData]);
    }
    public function getSelectTimeAjax()
    {
        return json_encode([
            'code'          =>  1,
            'msg'           =>  'success',
            'data'          =>  [
                'timeData'  =>  $this->timeData
            ]
        ]);
    }

    public function getCheckAjax(Request $request)
    {
        if($request->ajax())
        {
            $addressData = Address::where('uid', $this->user->id)->orderBy('id', 'desc')->get()->keyBy('id');
            $bacData = [];
            foreach ($addressData as $k=>$v)
            {
                $bacData[] = [
                    'id'        =>  $v->id,
                    'name'      =>  $v->name,
                    'phone'     =>  $v->phone,
                    'address'   =>  $v->address
                ];
            }
            return json_encode([
                'code'      =>  1,
                'msg'       =>  'success',
                'data'      =>  [
                    'address'   =>  $bacData,
                    'time'      =>  $this->timeData
                ]
            ]);
        }
    }

    /**
     * 创建订单
     * @param Request $request
     * @return string
     */
    public function postCreatOrder(Request $request)
    {
        $addressID = $request->has('addressID') ? $request->input('addressID') : 0;
        $delivery = $request->has('delivery') ? $request->input('delivery') : 0;
        $remark = $request->has('remark') ? $request->input('remark') : '';
        $dealData = $request->has('orderData') ? $request->input('orderData') : [];
        $orderDataForKey = [];
        //获取时间FORKEY
        $timeData = [];
        foreach ($this->timeData as $v)
        {
            $timeData[$v['id']] = $v;
        }
        foreach ($dealData as $v)
        {
            $orderDataForKey[$v['id']] = $v;
        }
        $storeID = \Illuminate\Support\Facades\Request::cookie('storeID') ? \Illuminate\Support\Facades\Request::cookie('storeID') : 1;

        $store = Store::find($storeID);
        //获取商品信息
        if(count($orderDataForKey) == 0)
            return json_encode([
                'code'      =>  0,
                'msg'       =>  'error'
            ]);
        $src = [];
        foreach ($orderDataForKey as $v)
        {
            array_push($src, $v['id']);
        }
        $cart = DB::table('shop_store_goods')
            ->join('shop_goods', 'shop_store_goods.goodsID', '=', 'shop_goods.id')
            ->whereIn('shop_store_goods.id', $src)
            ->select('shop_store_goods.id', 'shop_store_goods.storeID', 'shop_store_goods.amount', 'shop_store_goods.realAmount', 'shop_store_goods.number', 'shop_store_goods.display',
                'shop_goods.classifyID', 'shop_goods.title', 'shop_goods.thumb', 'shop_goods.abstract')
            ->orderBy('id', 'desc')
            ->get();
        $detail = [];
        $sum = 0;
        foreach($cart as $k=>$v)
        {
            $detail[] = [
                'id'        =>  $v->id,
                'title'     =>  $v->title,
                'thumb'     =>  $v->thumb,
                'num'       =>  $orderDataForKey[$v->id]['num'],
                'price'     =>  $v->realAmount
            ];
            $sum += $orderDataForKey[$v->id]['num'] * $v->realAmount;
        }
        $oldSum = $sum;
        //折扣
        $discount = $this->memberGroup[$this->user->groupID]->discount;
        if ($discount)
        {
            $sum = $sum * ($discount/10);
        }
        $price = 0;
        if ($oldSum < $timeData[$delivery]['term'])
        {
            $detail[] = [
                'title'     =>  '送料(商品总价低于 '.$timeData[$delivery]['term'].' 円)',
                'thumb'     =>  '',
                'num'       =>  1,
                'price'     =>  (double)$timeData[$delivery]['priceTwo']
            ];
            $price = (double)$timeData[$delivery]['priceTwo'];
        }else{
            $detail[] = [
                'title'     =>  '送料',
                'thumb'     =>  '',
                'num'       =>  1,
                'price'     =>  (double)$timeData[$delivery]['price']
            ];
            $price = (double)$timeData[$delivery]['price'];
        }
        $detail[] = [
            'title'     =>  '割引',
            'thumb'     =>  '',
            'num'       =>  1,
            'price'     =>  0,
            'discount'  =>  $discount
        ];

        //获取地址信息
        $addressData = Address::find($addressID);
        $sum += $price;

        //订单号
        $orderID = 'QGW'.$store->id.$this->getMillisecond().rand(1000,9999);
        $checkOrderID = \App\Models\Shop\Order::where('orderNumber', $orderID)->first();
        while($checkOrderID)
        {
            $orderID = 'QGW'.$store->id.$this->getMillisecond().rand(1000,9999);
        }
        $orderData = [
            'uid'               =>  $this->user->id,
            'address'           =>  '氏名：'.$addressData->name.'；電話：'.$addressData->phone.'；住所：'.$addressData->address,
            'shopTime'          =>  $timeData[$delivery]['time'],
            'orderNumber'       =>  $orderID,
            'storeID'           =>  $storeID,
            'orderList'         =>  json_encode($detail),
            'amount'            =>  round((double)$sum, 1),
            'payState'          =>  0,
            'logisticsState'    =>  0,
            'remark'            =>  $remark
        ];
        $check = \App\Models\Shop\Order::create($orderData);
        if($check)
        {
            return json_encode([
                'code'      =>  1,
                'msg'       =>  'success',
                'order'     =>  $orderID
            ]);
        }
        return json_encode([
            'code'      =>  0,
            'msg'       =>  'error'
        ]);
    }

    public function getPayment(Request $request)
    {
        $orderNumber = $request->has('code') ? $request->input('code') : false;
        if(!$orderNumber)
            return view('errors.404');
        $order = \App\Models\Shop\Order::where('uid', $this->user->id)->where('orderNumber', $orderNumber)->where('payState', 0)->first();
        if(!$order)
            return redirect()->action('Shop\IndexController@getIndex');
        $order->orderList = json_decode($order->orderList) ? json_decode($order->orderList) : $order->orderList;
        return view('shopWx.deal-payment')->with(['order' => $order]);
    }

    /**
     * stripe 支付
     * @param Request $request
     * @return $this|\Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function getPaymentStripe(Request $request)
    {
        $orderNumber = $request->has('code') ? $request->input('code') : false;
        if(!$orderNumber)
            return view('errors.404');
        $order = \App\Models\Shop\Order::where('uid', $this->user->id)->where('orderNumber', $orderNumber)->where('payState', 0)->first();
        if(!$order)
            return redirect()->action('Shop\IndexController@getIndex');
        $order->orderList = json_decode($order->orderList) ? json_decode($order->orderList) : $order->orderList;
        return view('shopWx.deal-payment-stripe')->with(['order' => $order]);
    }

    /**
     * 微信支付
     * @param Request $request
     * @return string
     */
    public function postPay(Request $request)
    {
        $code = $request->has('code') ? $request->input('code') : '';
        if ($code)
        {
            //获取订单信息
            $orderData = \App\Models\Shop\Order::where('orderNumber', $code)->where('payState', 0)->where('uid', $this->user->id)->first();
            if($orderData)
            {
                //获取学校名称
                $school = Store::find($orderData->storeID);
                $body = '厳選SHOPトクバイ商品-'.$school->name;
                $detail = [];
                $cart = json_decode($orderData->orderList);
                $oid = [];
                foreach($cart as $k=>$v)
                {
                    $detail[] = $v->title.' x '.$v->num.' | '.$v->price.' 円';
                    if(isset($v->id))
                        array_push($oid, $v->id);
                }
                $detail = implode(',', $detail);
                /*
                * 统一下单
                */
                $app = new Application(config('wechat'));
                $payment = $app->payment;
                $attributes = [
                    'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
                    'body'             => $body,
                    'detail'           => $detail,
                    'out_trade_no'     => $code,
                    'total_fee'        => $orderData->amount * 100,
                    'notify_url'       => action('Api\WechatController@postNotify'), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                    'openid'           => $this->user->openID, // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
                    // ...
                ];
                $order = new Order($attributes);

                $result = $payment->prepare($order);

                if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
                    $prepayId = $result->prepay_id;
                    $config = $payment->configForJSSDKPayment($prepayId);
                    $config['timeStamp'] = $config['timestamp'];
                    unset($config['timestamp']);

                    $backData = [
                        'code'      =>  1,
                        'msg'       =>  'success',
                        'config'    =>  $config,
                        'oid'       =>  $oid
                    ];
                    return json_encode($backData);
                }else{
                    $backData = [
                        'code'      =>  0,
                        'msg'       =>  'エラー',
                        'oid'       =>  $oid
                    ];

                    return json_encode($backData);
                }
            }
        }
    }

    public function postPayStripe(Request $request)
    {
        $code = $request->has('code') ? $request->input('code') : '';
        $stripeToken = $request->has('stripeToken') ? $request->input('stripeToken') : '';
        if ($code)
        {
            //获取订单信息
            $orderData = \App\Models\Shop\Order::where('orderNumber', $code)->where('payState', 0)->where('uid', $this->user->id)->first();
            if($orderData)
            {
                //获取学校名称
                $school = Store::find($orderData->storeID);
                $body = $school->name;
                $detail = [];
                $cart = json_decode($orderData->orderList);
                $oid = [];
                foreach($cart as $k=>$v)
                {
                    $detail[] = $v->title.' x '.$v->num.' | '.$v->price.' 円';
                    if(isset($v->id))
                        array_push($oid, $v->id);
                }
                $detail = implode(',', $detail);
                /*
                * 统一下单
                */
                $stripe = Omnipay::create('Stripe');
                $stripe->setApiKey('sk_test_5YmnvF9nFBiIkIvRmaToLDIU');

                $response = $stripe->purchase([
                    'amount' => round($orderData->amount,0),
                    'currency' => 'JPY',
                    'token' => $stripeToken,
                    'metadata'  =>  [
                        'orderID'    =>  $code
                    ]
                ])->send();

                if ($response->isRedirect()) {
                    // redirect to offsite payment gateway
                    $response->redirect();
                } elseif ($response->isSuccessful()) {
                    // payment was successful: update database
                    $backData = [
                        'code'      =>  1,
                        'msg'       =>  'success',
                        'oid'       =>  $oid
                    ];
                    return json_encode($backData);
                } else {
                    // payment failed: display message to customer
                    $backData = [
                        'code'      =>  0,
                        'msg'       =>  $response->getMessage(),
                        'oid'       =>  $oid
                    ];

                    return json_encode($backData);
                }
            }
        }
    }

    private function getMillisecond() {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
    }
}
